from app import db
from typing import Type, TypeVar, List, Optional, Any
from app.models.base import BaseModel
from app.utils.errors import NotFoundError

T = TypeVar('T', bound=BaseModel)

class DatabaseManager:
    @staticmethod
    def create(model: Type[T], data: dict) -> T:
        """创建记录"""
        instance = model.from_dict(data)
        db.session.add(instance)
        db.session.commit()
        return instance

    @staticmethod
    def get_by_id(model: Type[T], id: int) -> Optional[T]:
        """通过ID获取记录"""
        return model.query.get(id)

    @staticmethod
    def get_by_id_or_404(model: Type[T], id: int) -> T:
        """通过ID获取记录，不存在则抛出404错误"""
        instance = DatabaseManager.get_by_id(model, id)
        if not instance:
            raise NotFoundError(f"{model.__name__} with id {id} not found")
        return instance

    @staticmethod
    def update(instance: T, data: dict) -> T:
        """更新记录"""
        instance.update_from_dict(data)
        db.session.commit()
        return instance

    @staticmethod
    def delete(instance: T) -> None:
        """删除记录"""
        db.session.delete(instance)
        db.session.commit()

    @staticmethod
    def list_all(model: Type[T], **filters) -> List[T]:
        """获取所有记录"""
        query = model.query
        for key, value in filters.items():
            if hasattr(model, key):
                query = query.filter(getattr(model, key) == value)
        return query.all()

    @staticmethod
    def bulk_create(model: Type[T], instances: List[T]) -> None:
        """批量创建记录"""
        db.session.bulk_save_objects(instances)
        db.session.commit() 